<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <!-- 样式重置 -->
  <link rel="stylesheet" href="https://cdn.staticfile.org/normalize/8.0.1/normalize.min.css">
  <link rel="stylesheet" href="./css/index.css">
  <link rel="stylesheet" href="./css/elui-index.css">
  <title>添加攻略</title>
  <style>
    .setBaseStyle,
    .setDayStyle {
      width: 100%;
      box-sizing: border-box;
      margin-top: 10px;
      border: 1px solid saddlebrown;
    }
  </style>
</head>

<body>
  <div id="LsApp">
    <div class="left">
      <left-comp :point="point" :main-option="mainOption" :point-in-resource-data="pointInResourceData"
        @transmit-leftcompdata="transmitLeftCompData"
        @transmit-draggable-left-pointdata="transmitDraggableLeftPointdata" :cropper-option-data="cropperOptionData"
        @scroll-more="scrollMore" :point-resource-option="pointResourceOption">
      </left-comp>

    </div>
    <div class="mid" style="padding-bottom: 100px">
      <div class="setBaseStyle">
        <base-info :form-confirm="formConfirmNum" ref="baseInfoForm" :base-info-form="baseInfoForm"
          :base-info-cropper-option="cropperOptionData" @scroll-more="scrollMore" @remote-method="remoteMethod" :main-option="mainOption">
        </base-info>
      </div>
      <div class="setDayStyle">
        <point-comp :point="point" :main-option="mainOption" :day-comp-cropper-option="cropperOptionData"
          :point-in-resource-data="pointInResourceData" ref="pointCompForm" @scroll-more="scrollMore"
          :point-resource-option="pointResourceOption">
        </point-comp>
      </div>
      <el-button type="warning" size="mini" @click="confirm" v-if="mainOption.operate==='show'?false:true">提交</el-button>
    </div>
    <div class="right">
      <div class="phone-simulator">
        <simulator :point="point" :base-info-data="baseInfoForm.baseInfoData"></simulator>
      </div>
    </div>
  </div>
  <!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script> -->
  <script src="./plugin//axios.min.js"></script>
  <!-- 上线替换vue.min.js -->
  <script src="./plugin/vue.js"></script>
  <!-- 拖拽包 -->
  <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.7.0/Sortable.min.js"></script>
  <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.16.0/vuedraggable.min.js"></script> -->
  <script src="./plugin/vuedraggable.min.js"></script>
  <!-- vue图片裁剪 -->
  <!-- <script src="./plugin/vueCropper.min.js"></script> -->
  <script src="https://cdn.jsdelivr.net/npm/vue-cropper@0.4.9/dist/index.min.js"></script>
  <!-- element -->
  <script src="./plugin/elui-index.js"></script>
  <script src="./plugin/httpVueLoader.js"></script>
  <script src="./plugin/better-scroll.min.js"></script>
  <script src="./plugin/cos-js-sdk-v5.min.js"></script>
  <script>
    var author = 'show'
    function dispatch(that, componentName, eventName, params) {
      let parent = that.$parent || that.$root;
      let name = parent.$options.name;
      // while会一直循环
      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent;
        if (parent) {
          name = parent.$options.name;
        }
      }
      if (parent) {
        parent.$emit.apply(parent, [eventName].concat(params));
      }
    }
    var tagTypeFn = () => {
      const arr = ['', 'success', 'info', 'warning', 'danger']
      const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
      return arr[RandomNum(0, 4)]
    }
    var checkTag = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('tag不能为空'));
      } else if (value.length > 8) {
        callback(new Error('不能超过8个字符'))
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (value.length > 8) {
        callback(new Error('太长'));
      } else {
        callback()
      }
    };
    // 表单验证函数
    function allCheckRules(that, formName, index) {
      let result;
      result = new Promise((resolve, reject) => {
        if (index) {
          that.$refs[formName][0].validate(valid => {
            if (valid) {
              resolve();
            } else {
              reject();
            }
          });
        } else {
          that.$refs[formName].validate(valid => {
            if (valid) {
              resolve();
            } else {
              reject();
            }
          });
        }
      });
      return result;
    }
    // axios请求
    function http(url, method, data) {
      return new Promise((res, rej) => {
        axios({
          url,
          method,
          data
        })
          .then(pos => res(pos))
          .catch(err => rej(err));
      });
    }
    var Bucket = '';
    var Region = '';
    var config = {
      // url: 'https://newplay-leader.trip.wlkst.com/admin/'
      url: 'https://wl.fangkeng.wang/'
    }
    // 初始化COS上传图片
    var cos = new COS({
      getAuthorization: function (options, callback) {
        // var url = 'http://wl.fangkeng.wang/api/test/test';
        var url = config.url + 'admin/cosv5';
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.onload = function (e) {
          try {
            var data = JSON.parse(e.target.responseText);
            Bucket = data.Bucket;
            Region = data.Region;
          } catch (e) {
          }
          callback({
            TmpSecretId: data.credentials && data.credentials.tmpSecretId,
            TmpSecretKey: data.credentials && data.credentials.tmpSecretKey,
            XCosSecurityToken: data.credentials && data.credentials.sessionToken,
            ExpiredTime: data.expiredTime,
          });
        };
        xhr.send();
      }
    });
    var app = new Vue({
      name: 'LsApp',
      el: '#LsApp',
      data: {
        formData:
          { "thumb": "https://sun-1253313441.cos.ap-chengdu.myqcloud.com/images/1569395546888", "title": "攻略标题", "tag": ["撒旦"], "point": [{ "title": "GV好久", "play_time": 1.5, "content": [{ "val": "uiysafgduy1", "type": "text", "IsDel": false }, { "imgList": { "url": "https://sun-1253313441.cos.ap-chengdu.myqcloud.com/images/1569395844948" }, "type": "img", "IsDel": false }], "resources": [{ "id": 6, "title": "胖子鱼站", "thumb": "https://static.trip.wlkst.com/images/aecc43176ce8f2a46e3bca6d9b69b2fd.jpeg", "disabled": false, "IsDel": false }], "IsDel": false, "pointTitleMax": 50 }, { "title": "asd1", "play_time": 1, "content": [{ "val": "d1", "type": "text", "IsDel": false }, { "imgList": { "url": "https://sun-1253313441.cos.ap-chengdu.myqcloud.com/images/1569395868758" }, "type": "img", "IsDel": false }], "resources": [{ "id": 8, "title": "有一家小吃店", "thumb": "https://static.trip.wlkst.com/images/ea5626c22de46188d20bef98a6055130.jpeg", "disabled": false, "IsDel": false }], "IsDel": false, "pointTitleMax": 50 }], "scenics": [{ "id": 17, "title": "天生三桥玻璃眺台", "disabled": false }, { "id": 15, "title": "仙女山冰雪世界", "disabled": false }], "summary": "攻略简介攻略简介攻略简介攻略简介攻略简介攻略简介", "sort": 6, "state": 10 },
        mainOption: {
          name: 'strategy',
          operate: 'strategy',
          // summary: '',
          // summaryMax: 200,
          tiOption: {
            title: '',
            titleMax: 50,
            content: [],
            resources: [],
          },
          // 全局输入的配置
          globalOptionText: {
            contentTextMax: 200,
            autosize: {
              minRows: 2,
              maxRows: 10
            }
          },
        },
        // point里的资源数据index
        pointInResourceDataIndex: 1,
        // point里的资源数据
        pointInResourceData: [],
        // point的配置
        pointResourceOption: {
          // 默认数据
          data: [],
          searchArr: [],
          val: [],
          currentIndex: 1,
          searchIndex: 1,
          nowQuery: ''
        },
        // 资源是否必填
        rulesResource: [
          { required: false, message: "请选择资源", trigger: "blur", type: "array" }
        ],
        // 全局img的配置
        cropperOptionData: {
          img: "",
          size: 1,
          full: false,
          outputType: "png",
          canMove: true,
          // fixedBox为true就不能改变裁剪框
          fixedBox: false,
          original: false,
          canMoveBox: true,
          autoCrop: true,
          // 只有自动截图开启 宽度高度才生效
          autoCropWidth: 400,
          autoCropHeight: 350,
          centerBox: false,
          high: true
        },
        // 全局text的配置
        optionText: {
          // 字数
          max: 50,
          autosize: {
            minRows: 2,
            maxRows: 10
          }
        },
        // 当前天的index
        dayIndex: 0,
        pushPointState: false,

        // day的数据
        // day: [],
        point: [],
        formConfirmNum: 0,
        // baseinfo 的表单和值
        baseInfoForm: {
          baseInfoData: [
            {
              label: "攻略标题",
              rules: [
                { required: true, message: "请输入攻略标题", trigger: "blur" }
              ],
              val: "",
              solt: false,
              type: "input",
              option: { max: "20" },
              placeholder: "请输入攻略标题"
            },
            {
              label: "头图",
              rules: [{ required: true, message: "请添加头图", trigger: "blur" }],
              solt: true,
              val: "",
              type: "button",
              buttonText: "浏览"
            },
            {
              label: "攻略简介",
              rules: [
                { required: true, message: "请输入攻略简介", trigger: "blur" }
              ],
              val: "",
              solt: false,
              type: "areaInput",
              option: {
                max: "500"
              },
              placeholder: "请输入攻略简介"
            },
            {
              label: "标签",
              // rules: [{ required: true, message: "请输入标签", trigger: "blur" }],
              rules: [{ validator: checkTag, trigger: 'blur', required: true }],
              val: [],
              solt: false,
              tagType: tagTypeFn(),
              type: "tag",
              // v-model
              vm: "",
              TagInputVisible: false,
              tagText: "+ New Tag",
              placeholder: "请输入标签(1-8)个字符"
            },
            {
              label: '关联景点',
              rules: [{ required: false, message: "请选择关联景点", trigger: "blur" }],
              val: [],
              type: 'option',
              data: [],
              searchArr: [],
              changeIf: 'scenic',
              placeholder: "请输入关联景点 关键词",
              name: 'strategyTheScenic',
              currentIndex: 1,
              searchIndex: 1,
              nowQuery: ''
            },
            {
              label: "排序(0~1000)",
              rules: [],
              val: "",
              solt: false,
              type: "number",
              option: {
                // 保留小数
                precision: 0,
                // 每次加1
                step: 1
              }
            },
            {
              label: "发布",
              rules: [],
              val: true,
              solt: false,
              type: "bool"
            }
          ]
        },
      },
      components: {
        'left-comp': httpVueLoader('./components/strategyLeft.vue'),
        'base-info': httpVueLoader('./components/baseInfo.vue'),
        'point-comp': httpVueLoader('./components/strategyPointComp.vue'),
        'simulator': httpVueLoader('./components/simulator/strategySimulator.vue')
      },
      created() {
        // 初始化 关联景点
        this.strategyInScenicList('', 10, 1)
        // point里的资源数据
        this.pointResouceList('', 10, 1)
        if (author === 'create') {
          // 新增
          this.mainOption.operate = 'create'
        } else if (author === 'edit') {
          this.mainOption.operate = 'edit'
          // 修改
          this.userOperate()
        } else {
          // 查看
          this.mainOption.operate = 'show'
          this.userOperate()
        }
      },
      mounted() {
        this.$on('scroll-more', (name) => {
          this.scrollMore(name)
        })
        this.$on('remote-method', (obj) => {
          console.log(obj, 'obj')
          this.remoteMethod(obj)
        })
      },
      methods: {
        userOperate() {
          let data = this.formData
          let baseData = this.baseInfoForm.baseInfoData
          let point = this.point
          baseData[1].val = data.thumb
          baseData[0].val = data.title
          baseData[3].val = data.tag
          this.point = data.point
          baseData[4].val = data.scenics
          baseData[2].val = data.summary
          baseData[5].val = data.sort
          baseData[6].val  = data.state===10 ? true : false
        },
        unique(arr) {
          const res = new Map();
          return arr.filter(arr => !res.has(arr.id) && res.set(arr.id, 1));
        },
        remoteMethod(obj) {
          if (obj.name === 'strategyTheScenic') {
            this.baseInfoForm.baseInfoData[4].searchIndex = 1;
            this.baseInfoForm.baseInfoData[4].searchArr = this.baseInfoForm.baseInfoData[4].val.concat([]);
            this.baseInfoForm.baseInfoData[4].nowQuery = obj.query
            // const count = ++this.baseInfoForm.baseInfoData[4].currentIndex
            obj.query && this.strategyInScenicList(obj.query, 10, 1, 'search')
          } else {
            // const count = ++this.pointInResourceDataIndex
            console.log(obj, 'remoteMethod obj')
            this.pointResourceOption.searchIndex = 1;
            if (obj.transmitName === 'content') {
              this.pointResourceOption.searchArr = this.point[obj.pointIndex].resources.concat([])
            } else {
              this.pointResourceOption.searchArr = this.pointResourceOption.val.concat([]);
            }
            this.pointResourceOption.nowQuery = obj.query
            obj.query && this.pointResouceList(obj.query, 10, 1, 'search')
          }
        },
        scrollMore(name) {
          // 关联景点
          if (name === 'strategyTheScenic') {
            const nowQuery = this.baseInfoForm.baseInfoData[4].nowQuery
            const count = nowQuery ? ++this.baseInfoForm.baseInfoData[4].searchIndex : ++this.baseInfoForm.baseInfoData[4].currentIndex
            // const count = ++this.baseInfoForm.baseInfoData[4].currentIndex
            this.strategyInScenicList(nowQuery, 10, count)
          } else {
            // const count = ++this.pointInResourceDataIndex
            const nowQuery = this.pointResourceOption.nowQuery
            const count = nowQuery ? ++this.pointResourceOption.searchIndex : ++this.pointResourceOption.currentIndex
            this.pointResouceList(nowQuery, 10, count)
          }
        },
        // point里的资源数据
        pointResouceList(search, page_size, page, isSearch) {
          this.getListHttp('api/v1/getResource', "POST", { search, page_size, page, type: 1 }, isSearch)
          // this.getListHttp('api/v1/test', "POST", { search, page_size, page, type: 1 }, '', isSearch)
        },
        // 攻略获取景点
        strategyInScenicList(search, page_size, page, isSearch) {
          this.getListHttp('api/v1/getScenic', "POST", { search, page_size, page }, 4, isSearch)
          // this.getListHttp('api/v1/test', "POST", { search, page_size, page }, 4, isSearch)
        },
        getListHttp(strUrl, methods, objData, index, isSearch) {
          const that = this
          http(config.url + strUrl, methods, objData).then(pos => {
            const list = pos.data.data
            list.data.map((item, index) => {
              item.disabled = false
            })
            if (index) {
              if (isSearch) {
                that.baseInfoForm.baseInfoData[index].searchArr = this.unique(that.baseInfoForm.baseInfoData[index].searchArr.concat(list.data))
              } else {
                that.baseInfoForm.baseInfoData[index].data = this.unique(that.baseInfoForm.baseInfoData[index].data.concat(list.data))
              }
              // if (objData.page <= list.last_page) {
              //   that.baseInfoForm.baseInfoData[index].data = list.data.concat(that.baseInfoForm.baseInfoData[index].data)
              // }
            } else {
              if (isSearch) {
                that.pointResourceOption.searchArr = this.unique(that.pointResourceOption.searchArr.concat(list.data))
              } else {
                that.pointResourceOption.data = this.unique(that.pointResourceOption.data.concat(list.data))
              }
              // that.pointInResourceData = list.data.concat(that.pointInResourceData)
            }
            console.log(pos)
          }).catch(err => {
            console.log(err, 'err')
          })
        },
        transmitDraggableLeftPointdata(obj) {
          this.point = obj.dataNewPoint
        },
        tagTypeFn() {
          const arr = ['', 'success', 'info', 'warning', 'danger']
          const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
          return arr[RandomNum(0, 4)]
        },
        // left point传来的数据
        transmitLeftCompData(data) {
          this.point.push(data.obj)
        },
        confirm() {
          // this.formConfirmNum++
          let arr = []
          let baseForm = this.$refs.baseInfoForm.runFormConfirm()
          // let pointForm = this.$refs.pointCompForm.runDayForm()
          arr.push(baseForm)
          // arr.concat(pointForm)
          Promise.all(arr)
            .then(() => {
              //都通过了
              console.log("yyes");
              let data = {}
              let baseData = this.baseInfoForm.baseInfoData
              let point = this.point
              data.thumb = baseData[1].val
              data.title = baseData[0].val
              data.tag = baseData[3].val
              data.point = point
              data.scenics = baseData[4].val
              data.summary = baseData[2].val
              data.sort = baseData[5].val
              data.state = baseData[6].val ? 10 : 0
              this.formData = data
              http(config.url + 'api/v1/strategyUpdateOrCreate', 'POST', data).then(pos => {
                console.log(pos, 'pos confirm')
                const code = pos.data.code
                if (code === 0) {
                  this.$message({ message: "上传成功", type: "success" });
                } else {
                  this.$message({ message: "上传失败", type: "error" });
                }
              }).catch(err => {
                console.log(err, 'err confirm')
              })
            })
            .catch(err => {
              this.$message({ message: "请填写完整信息", type: "warning" });
              console.log("err", err);
            });
        },
      }
    })


    const selectDown = Vue.directive('loadmore', {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        SELECTWRAP_DOM.addEventListener('scroll', function () {

          const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight
          if (CONDITION) {
            binding.value()
          }
        })
      }
    })
    Vue.use(selectDown)
  </script>
</body>

</html>